import { nextTick } from 'vue'
import html2canvas from 'html2canvas'
export function useHtml2Canvas() {
  // 返回base64及data
  const getBase64 = function (url) {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.setAttribute('crossOrigin', 'Anonymous')
      img.onload = function () {
        const base64 = getImgBase64(img)
        if (base64) {
          resolve(base64)
        } else {
          reject()
        }
        // return base64
      }
      img.src = url
    })
  }

  const getImgBase64 = function (img) {
    const canvas = document.createElement('canvas')
    canvas.width = img.width
    canvas.height = img.height
    var ctx = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0, img.width, img.height)
    let idx = img.src.lastIndexOf('.')
    var ext = img.src.slice(idx + 1).toLowerCase()
    if (ext == 'jpg') ext = 'jpeg'
    var dataUrl = canvas.toDataURL('images/' + ext)
    return dataUrl
  }

  // html2canvas domId范围有图片 需要避免跨域 加useCORS: true 或者 转成base64
  const htmlToImg = async function (domId, cb) {
    window.pageYoffset = 0
    document.documentElement.scrollTop = 0
    document.body.scrollTop = 0
    await nextTick()
    html2canvas(document.getElementById(domId), {
      height: document.getElementById(domId).scrollHeight,
      windowHeight: document.getElementById(domId).scrollHeight,
      useCORS: true,
    }).then((canvas) => {
      const imgUrl = canvas.toDataURL('image/png')
      cb(imgUrl)
    })
  }
  const downloadBase64ToImg = function (content, fileName) {
    //下载base64图片
    var base64ToBlob = function (code) {
      let parts = code.split(';base64,')
      let contentType = parts[0].split(':')[1]
      let raw = window.atob(parts[1])
      let rawLength = raw.length
      let uInt8Array = new Uint8Array(rawLength)
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], {
        type: contentType,
      })
    }
    let aLink = document.createElement('a')
    let blob = base64ToBlob(content) //new Blob([content]);
    let evt = document.createEvent('HTMLEvents')
    //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    evt.initEvent('click', true, true)
    aLink.download = fileName
    aLink.href = URL.createObjectURL(blob)
    aLink.click()
  }
  return {
    getBase64,
    getImgBase64,
    htmlToImg,
    downloadBase64ToImg,
  }
}
